package org.yanwensiyi.maomamabot.bot

import net.mamoe.mirai.Bot
import net.mamoe.mirai.BotFactory
import net.mamoe.mirai.event.events.FriendMessageEvent
import net.mamoe.mirai.event.events.GroupMessageEvent
import net.mamoe.mirai.event.events.GroupTempMessageEvent
import net.mamoe.mirai.utils.MiraiLogger
import java.nio.file.FileSystems
import java.nio.file.Path
import java.nio.file.StandardWatchEventKinds

class Bot(qq: Long, password: String) {
    val bot: Bot = BotFactory.newBot(qq, password)
    val logger: MiraiLogger = bot.logger
    private val dispatchers = Array(10) { Dispatcher(this) }

    init {
        initWatcher()
        listenEvents()
    }

    /**
     * 开始监听事件并且传递给dispatcher
     */
    private fun listenEvents() {
        bot.eventChannel.subscribeAlways(GroupMessageEvent::class) {
            Dispatcher.offer(it)
        }
        bot.eventChannel.subscribeAlways(FriendMessageEvent::class) {
            Dispatcher.offer(it)
        }
        bot.eventChannel.subscribeAlways(GroupTempMessageEvent::class) {
            Dispatcher.offer(it)
        }
    }

    fun info(msg: String) = logger.info(msg)

    /**
     * 初始化文件系统观察者
     */
    private fun initWatcher() {
        val fs = FileSystems.getDefault()
        val watcher = fs.newWatchService()
        Path.of("js").register(
            watcher,
            StandardWatchEventKinds.ENTRY_CREATE,
            StandardWatchEventKinds.ENTRY_DELETE,
            StandardWatchEventKinds.ENTRY_MODIFY
        )
        while (true) {
            val key = watcher.take()
            //重新加载所有插件
            //initScriptContext()
            key.reset()
        }
    }
}